#include <iostream>
#include <sstream>
#include <fstream>
#include <vector>
using std::cout;
using std::endl;
using std::vector;
using std::string;
using std::ifstream;
using std::ofstream;
using std::istringstream;


struct Record
{
	string _word;
	int _frequency;
};

class Dictionary
{
public:
    void read(const std::string &filename);
    void store(const std::string &filename);
private:
    vector<Record> _dict;
};

void Dictionary::read(const string & filename){
    ifstream ifs(filename);
    if(!ifs.good()){
        cout << "fail to open file" << endl;
        return;
    }

    string line;
    while(getline(ifs,line)){
        istringstream iss(line);
        string word;
        while(iss >> word){
            //处理数字问题
            bool hasDigit = false;
            for(auto & ch : word){
                if(isdigit(ch)){
                    hasDigit = true;
                    break;
                }
            }

            if(hasDigit){
                continue;
            }
            
            //处理标点符号
            //如果单词末尾出现符号，不统计
            if(ispunct(word.back())){
                continue;
            }

            //如果单词开头出现符号，不统计
            if(ispunct(word.front())){
                continue;
            }

            //如果单词首字母大写，转成小写
            if(isupper(word[0])){
                word[0] = tolower(word[0]);
            }

            bool isExist = false;
            for(auto & ele : _dict){
                if(word == ele._word){
                    ++ele._frequency;
                    isExist = true;
                    break;
                }
            }

            if(!isExist){
                Record rec;
                rec._word = word;
                rec._frequency = 1;
                _dict.push_back(rec);
            }

        }
    }
    ifs.close();
}

void Dictionary::store(const string & filename)
{
    ofstream ofs(filename);
    for(auto & rec : _dict){
        ofs << rec._word << "  :   " << rec._frequency << endl;
    }
    ofs.close();
}

void test0(){
    string filename("The_Holy_Bible.txt");
    string result("dict.txt");

    Dictionary dict;
    dict.read(filename);
    dict.store(result);
}

int main(void){
    test0();
    return 0;
}
